package yesterday;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/9/30 8:10
 * @Description: 请求中包含中文字段的编码问题解析
 */
@WebServlet(name = "questEncodeServlet", urlPatterns = {"/requestEncode"})
public class RequestEncodeServlet extends HttpServlet {


  @Override
  protected void doGet(HttpServletRequest req,
      HttpServletResponse resp)
      throws ServletException, IOException {
    String rawName = req.getParameter("name");
    if (rawName == null) {
      rawName = new String("hello world i add".getBytes( "iso-8859-1"));
    }
    String zhName  = new String(rawName.getBytes("iso-8859-1"), "utf-8");
    System.out.println(rawName);
    System.out.println(zhName);

    resp.addHeader("a", "xxxxxxx1");
    resp.addHeader("a", "xxxxxxx2");
    resp.addHeader("b", "yyyyyyy");
    resp.setHeader("a", "xxxxxxx3");
    resp.addHeader("content-type", "text/html;charset=UTF-8");
    resp.getWriter().println("hello world");
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    String rawName = req.getParameter("name");
    System.out.println(rawName);
  }
}
